/****************************************************************************
*
* Description: Singleton idioma
* Created at: 25.11.06 23:16:06 UTC
*
* $Revision$
*
****************************************************************************/
#pragma once

#if !defined(__common_singleton_h__)
#define __common_singleton_h__

#include <boost/utility.hpp>

namespace  common {

/* Boost library does not provide singleton itself, but has few
 * implementations in different modules. I took one and use it as standard
 * primitive.  */

// T must be: no-throw default constructible and no-throw destructible
template <typename T>
struct singleton : boost::noncopyable
{
  private:
    struct object_creator
    {
      // This constructor does nothing more than ensure that instance()
      //  is called before main() begins, thus creating the static
      //  T object before multithreading race issues can come up.
      object_creator() { singleton<T>::instance(); }
      inline void do_nothing() const { }
    };
    static object_creator create_object;

    singleton();

  public:
    typedef T object_type;

    // If, at any point (in user code), singleton_default<T>::instance()
    //  is called, then the following function is instantiated.
    static object_type & instance()
    {
      // This is the object that we return a reference to.
      // It is guaranteed to be created before main() begins because of
      //  the next line.
      static object_type obj;

      // The following line does nothing else than force the instantiation
      //  of singleton_default<T>::create_object, whose constructor is
      //  called before main() begins.
      create_object.do_nothing();

      return obj;
    }
};

template <typename T>
typename singleton<T>::object_creator
singleton<T>::create_object;

} /* End of namespace common.  */

#endif /* End of __common_singleton_h__.  */
